import { getSetting, chooseAddress, openSetting,showModal,showToast,requestPayment} from "../../utils/asyncWx.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
import {request} from '../../request/index.js'
Page({
  data: {
    address:{},
    cart:[],
    allChecked:false,
    totalPrice:0,
    totalNum:0
  },
  onShow:function(){
    let address = wx.getStorageSync('address');
    let cart = wx.getStorageSync('cart')||[];
    this.setData({address});
    cart = cart.filter(v=>v.checked);
   
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v=>{
      if(v.checked){
        totalPrice += v.num*v.goods_price;
        totalNum += v.num;
      }
    })
    this.setData({
      cart,
      totalNum,
      totalPrice
    })
  },
  async handlePay(){
    const token = wx.getStorageSync('token');
    if(!token){
      wx.navigateTo({
        url: '/pages/auth/index',
      });   
    }else{
      try {
        const header = {Authorization:token};
        const order_price = this.data.totalPrice;
        const consignee_addr = this.data.address.all;
        const cart = this.data.cart;
        let goods = [];
        cart.forEach(v=>goods.push({
          goods_id:v.goods_id,
          goods_number:v.goods_number,
          goods_price:v.goods_price
        }))
        const orderParams = {order_price,consignee_addr,goods};
        //发送请求
        //const {order_number} = await request({url:"/my/orders/create",method:'POST',data:orderParams,header});
        const order_number = 'HMDD281988098808001959';
        //发起预支付
        //const {pay} = await request({url:'/my/orders/req_unifiedorder',method:'POST',data:{order_number},header});
        const pay = {
          noncestr: "U6tYjNdYvm3ReKgI", 
          package: "prepay_ id wx89182118356982a15c8b8d871931343000",
          paySign: "C514E29387794F 84004C983AFFF4787F",
          signType: "MD5",
          timestamp: Date.now()
        }
        //console.log(pay);
        //发起支付
        //await requestPayment(pay);
        //获取订单状态
        //const {status} = await request({url:'/my/orders/chkOrder',method:'POST',data:{order_number},header});
        // 支付成功要在购物车中删除已经支付的商品
        let newCart =wx.getStorageSync('cart');
        newCart = newCart.filter(v=>!v.checked);
        wx.setStorageSync('cart',newCart);
          
        await showToast({title:"订单支付成功"});
        wx.navigateTo({
          url:'/pages/order/index'
        })
      } catch (error) {
        await showToast({title:"订单支付失败"});
      }
    }
  }
})